﻿using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.WriteAPI.Applications.Commands.Depts;
using MediatR;

namespace B.S.Meeting.WriteAPI.Applications.CommandHandlers.Depts
{
    public class DelDeptCommandHandler : IRequestHandler<DelDeptCommand, APIResult<int>>
    {
        IBaseRepository<Dept> dRep;
        ILogger<DelDeptCommandHandler> logger;

        public DelDeptCommandHandler(IBaseRepository<Dept> dRep, ILogger<DelDeptCommandHandler> logger)
        {
            this.dRep = dRep;
            this.logger = logger;
        }

        public async Task<APIResult<int>> Handle(DelDeptCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var dept = await dRep.GetByIdAsync(request.DeptId);
                if (dept == null)
                {
                    return new APIResult<int>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "未找到指定的部门",
                        Data = 0
                    };
                }
                await dRep.Del(request.DeptId); // 直接调用仓储层的删除方法进行物理删除
                logger.LogInformation($"成功删除部门: ID {request.DeptId}");
                return new APIResult<int>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "删除成功",
                    Data = 1
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
